var express = require('express');
var jwt = require('jsonwebtoken');
var router = express.Router();

const moment = require('moment');

const AccountModel = require('../../models/AccountModel');
let checkTokenMiddleware = require('../../Middleware/checkTokenMiddleware');



// 记账本列表
router.get('/account', checkTokenMiddleware,function (req, res, next) {
    AccountModel.find()
        .sort({ time: -1 })
        .then((data) => {
            res.json({
                code: '0',
                msg: '读取成功',
                data: data,
            })
        }, (err) => {
            res.json({
                code: '1',
                msg: '读取失败',
                data: err,
            })
        });
});
router.get('/account/:_id', checkTokenMiddleware,function (req, res, next) {
    // console.log(req.user);
    let _id = req.params._id;
    AccountModel.findById(_id)
        .then((data) => {
            res.json({
                code: '0',
                msg: '读取成功',
                data: data,
            })
        }, (err) => {
            res.json({
                code: '1',
                msg: '读取失败',
                data: err,
            })
        });
});
router.patch('/account/:_id',checkTokenMiddleware, function (req, res, next) {
    let _id = req.params._id;
    AccountModel.updateOne({ _id }, { ...req.body })
        .then((data) => {
            res.json({
                code: '0',
                msg: '更新成功',
                data: data,
            })
        }, (err) => {
            res.json({
                code: '1',
                msg: '更新失败',
                data: err,
            })
        });
});
router.post('/account',checkTokenMiddleware, (req, res, next) => {
    // 写入信息
    // 时间戳(秒)
    AccountModel.create({
        ...req.body,
        time: moment(req.body.time).unix(),
    }).then((data) => {
        res.json({
            code: '0',
            msg: '添加成功',
            data: data,
        })
    }, (err) => {
        res.json({
            code: '1',
            msg: '添加失败',
            data: err,
        })
    })
});

router.delete('/account/:_id', checkTokenMiddleware,(req, res, next) => {
    // 获取id
    let _id = req.params._id;
    console.log(_id);
    AccountModel.deleteOne({ _id: _id })
        .then(() => {
            res.json({
                code: '0',
                msg: '删除成功',
                data: null,
            })
        }, err => {
            res.json({
                code: '1',
                msg: '删除失败',
                data: err,
            })
        })
    // // 删除
})
module.exports = router;
